﻿@using DCMS.Web.Framework;
@using DCMS.Web.Framework.UI;
@using DCMS.ViewModel.Models.Terminals;

@model TerminalListModel
<!-- Start: Content -->
<section id="content_wrapper">
    <!-- Start: Topbar-Dropdown -->
    <div id="topbar-dropmenu">
        <div id="topbar-dropmenu">
            @await Html.PartialAsync("_ToolBox")
        </div>
    </div>
    <!-- End: Topbar-Dropdown -->
    <!-- Start: Topbar -->
    <header id="topbar">
        <div class="topbar-left">
            <ol class="breadcrumb">
                <li class="crumb-active">
                    <a href="#">档案</a>
                </li>
                <li class="crumb-icon">
                    <a href="@Url.RouteUrl("HomePage")">
                        <span class="glyphicon glyphicon-home"></span>
                    </a>
                </li>
                <li class="crumb-link">
                    <a href="#">往来相关</a>
                </li>
                <li class="crumb-trail">终端档案</li>
            </ol>
        </div>
        <div class="topbar-right">
            <div class="ml15 ib va-m" id="toggle_sidemenu_r">
                <a href="#" class="pl5">
                    <i class="fa fa-sign-in fs22 text-primary"></i>
                    <span class="badge badge-hero badge-danger">3</span>
                </a>
            </div>
        </div>
    </header>
    <!-- End: Topbar -->
    <!-- Begin: Content -->
    <section id="content">

        <div class="special-alerts">
            <div class="alert alert-danger light alert-dismissable" id="alert-demo-2" style="display: none;">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                <i class="fa fa-info pr10"></i>
                <strong>您没有被授权此操作!</strong>
            </div>
        </div>

        <div class="row">
            <div class="col-md-2">
                <div class="panel">
                    <div class="panel-heading">
                        <div class="pull-left">
                            终端片区
                        </div>
                        <div class="pull-right">
                            <a id="btn_add_pq" href="javascript:;" class="mr5"><span class="glyphicon glyphicon-plus"></span></a>
                            <a id="btn_edit_pq" href="javascript:;" class="mr5"><span class="glyphicon glyphicon-pencil"></span></a>
                            <a id="btn_del_pq" href="javascript:;" class="mr5"><span class="glyphicon glyphicon-trash"></span></a>
                        </div>
                    </div>
                    <div class="panel-body">
                        <input type="hidden" name="TerminalDistrictId" id="TerminalDistrictId" value="0" />
                        <div id="tree"> </div>
                    </div>
                </div>
            </div>
            <div class="col-md-10">
                <div class="row mb10">
                    @*Toolbar*@
                    <div class="col-md-12">
                        <div class="pull-left mr10">
                            <div class="row mb10">
                                <div class="col-md-12">
                                    <select class="form-control" id="ddl_Status" name="ddl_Status">
                                        <option value="true">展示可用终端</option>
                                        <option value="false">展示停用终端</option>
                                        <option value="null">全部</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="pull-left mr10">
                            @*<dcms-select asp-for="ddl_Channel" asp-items="@Model.ChannelList" class="form-control" />*@
                        </div>
                        <div class="pull-left mr10">
                            @*@Html.DropDownList("ddl_Rank", Model.RankList, "-等级-"" class = "form-control"/>*@
                            @*<dcms-select asp-for="ddl_Rank" asp-items="@Model.RankList" class="form-control" />*@
                        </div>
                        <div class="input-group w400 pull-left">
                            <input type="text" id="txt_searchStr" class="form-control" placeholder="请输入终端名称、终端编号、老板名称、老板手机" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">
                            <span class="input-group-btn">
                                <button id="btn_query" type="button" class="btn btn-primary"><span class="glyphicon glyphicon-search"></span> 搜索</button>
                            </span>
                        </div>
                        <div class="pull-right">


                            <div class="btn-group">
                                <button type="button" class="multiselect dropdown-toggle btn btn-default" data-toggle="dropdown" title="Mozzarella" aria-expanded="false">批量操作 <b class="caret"></b></button>
                                <ul class="multiselect-container dropdown-menu">
                                    <li>
                                        <a href="javascript:void(0);" id="multiDelete">
                                            <label class="radio"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 批量删除</label>
                                        </a>
                                    </li>
                                    <li>
                                        <a href="javascript:void(0);" id="batchAssignDistrict">
                                            <label class="radio"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 批量指定片区</label>
                                        </a>
                                    </li>
                                    <li>
                                        <a href="javascript:void(0);" id="allAssignDistrict">
                                            <label class="radio"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 全部指定片区</label>
                                        </a>
                                    </li>
                                    <li>
                                        <a href="javascript:void(0);" id="batchAssignChannel">
                                            <label class="radio"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 批量指定渠道</label>
                                        </a>
                                    </li>
                                    <li>
                                        <a href="javascript:void(0);" id="allAssignChannel">
                                            <label class="radio"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 批量指定渠道</label>
                                        </a>
                                    </li>
                                    <li>
                                        <a href="javascript:void(0);" id="batchAssignRank">
                                            <label class="radio"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 批量指定客户等级</label>
                                        </a>
                                    </li>
                                    <li>
                                        <a href="javascript:void(0);" id="batchAssignPayments">
                                            <label class="radio"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 批量指定付款方式</label>
                                        </a>
                                    </li>
                                </ul>
                            </div>
                            <div class="pull-left">
                                @*<input type="checkbox" id="showTingyong" value="yes"> 显示停用终端*@
                            </div>

                            <button id="btn_batchDisable" type="button" class="btn btn-danger">
                                <span class="fa fa-trash-o mr5" aria-hidden="true"></span>批量禁用
                            </button>

                            <button id="btn_add" type="button" class="btn btn-primary">
                                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>添加
                            </button>
                            <button id="btn_importProduct" type="button" class="btn btn-info">
                                <span class="glyphicon glyphicon-import mr5" aria-hidden="true"></span> 导入
                            </button>
                            @*<button id="btn_expoertProduct" type="button" class="btn btn-info">
            <span class="glyphicon glyphicon-export mr5" aria-hidden="true"></span> 导出
        </button>*@
                            @*<button id="btn_edit" type="button" class="btn btn-info">
            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>编辑
        </button>
        <button id="btn_delete" type="button" class="btn btn-danger">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
        </button>*@

                        </div>
                    </div>
                </div>
                <div class="panel">
                    <div class="panel-heading">
                        <span class="panel-title">
                            <span class="glyphicon glyphicon-th"></span>终端列表
                        </span>
                    </div>
                    <div class="panel-body p5">
                        <table id="datatable" class="table table-striped table-bordered table-hover"></table>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <!-- End: Content -->
    <input id="hid_DistrictId" type="hidden" value="0" />
    <input id="hid_AssignDistrictId" type="hidden" value="0" />
    <input id="hid_AssignChannelId" type="hidden" value="0" />
</section>

<div id="TerFileForm" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">导入数据</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" asp-action="Import" asp-controller="Terminal" asp-route-returnurl="@Context.Request.Query["ReturnUrl"]" method="Post" id="formImport" novalidate="novalidate" enctype="multipart/form-data">

                    <input id="hidDistrictId" name="hidDistrictId" type="hidden" value="" />

                    <div class="row" style="text-align:center;">
                        <label for="file" class="field file state-success">
                            <input type="file" class="gui-file" name="file" id="file" accept=".xls,.xlsx" aria-required="true" aria-invalid="false">
                        </label>
                        @*<input type="submit" name="submit" value="导入" class="btn btn-info" />*@
                        <input id="excel_import" type="button" value="导入" class="btn btn-info" />
                        <a id="btn_down" href="@Url.Action("UploadDown","Terminal")" class="btn btn-success">
                            <span class="glyphicon glyphicon-export mr5"></span>下载模板
                        </a>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <div class="alert alert-info alert-dismissable" style="padding:0;">
                    <i class="fa fa-warning pr10"></i>
                    <strong style="margin-right:40px;"> 温馨提示：请先下载模板，按照模板填写数据进行导入！</strong>
                    <button type="button" class="btn btn-default btn-sm" data-dismiss="modal"><i class="fa fa-undo mr5"></i>取消</button>
                </div>

            </div>
        </div>
    </div>
</div>

@{
    await Html.RenderPartialAsync("_ModalForm", new ViewDataDictionary(ViewData) { { "formId", "TerminalSelectForm" }, { "modalWindow", "TerminalSelectModalWindow" }, { "windowWidth", "900px" }, { "enctype", "multipart/form-data" }, { "method", "post" }, { "showSave", "true" } });
    await Html.RenderPartialAsync("_ModalForm", new ViewDataDictionary(ViewData) { { "formId", "DistrictSelectForm" }, { "modalWindow", "DistrictSelectModalWindow" }, { "windowWidth", "680px" }, { "showSave", "true" } });
    await Html.RenderPartialAsync("_ModalForm", new ViewDataDictionary(ViewData) { { "formId", "BatchAssignDistrictForm" }, { "modalWindow", "BatchAssignDistrictModalWindow" }, { "windowWidth", "680px" }, { "showSave", "true" } });
    await Html.RenderPartialAsync("_ModalForm", new ViewDataDictionary(ViewData) { { "formId", "BatchAssignChannelForm" }, { "modalWindow", "BatchAssignChannelModalWindow" }, { "windowWidth", "680px" }, { "showSave", "true" } });
}


@section CurPageScripts
{
    <script type="text/javascript" src="https://api.map.baidu.com/getscript?v=2.0&ak=bB75lKXKUHnI2o0dbND5ktWFSWOEg5Tv"></script>
    <script type="text/javascript" src="https://api.map.baidu.com/library/AreaRestriction/1.2/src/AreaRestriction_min.js"></script>
    <script type="text/javascript">
        jQuery(document).ready(function () {
            "use strict";
            // Init Theme Core
            Core.init({
                sbm: "sb-l-c",
            });
            // Init Demo JS
            Demo.init();

            //权限提示
            if ($(this).getUrlQueryString("Authorize") == "noAuthorize") {
                $('#alert-demo-2').fadeToggle();
                setTimeout(function () {
                    $('#alert-demo-2').fadeToggle();
                }, 3000);
            }

            //====================================================片区开始==========================================================================
            //左侧终端片区树控件
            var treeData = [];
            treeData.push({ id: 0, title: " 全部", expanded: true, folder:false, children: [] });
            var getTreeData = function () {
                $.ajax({
                    url: "/Terminal/GetDistrictFancyTree",
                    async: true,
                    success: function (res) {
                        if (res != null){
                            if (res.length != 0) {
                                var node = treeData.find(item => item.id == 0);
                                node.folder = true;
                                node.expanded = true;
                                node.children = res;
                            }
                        }
                        $('#tree').fancytree("getTree").reload(treeData);
                    }
                });
            }
            $('#tree').fancytree({
                extensions: ["dnd", "edit"],
                //titlesTabbable: true,
                debugLevel: 2,
                source: treeData,
                //source: getTreeData(),
                dnd: {
                    autoExpandMS: 400,
                    focusOnClick: true,
                    preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
                    preventRecursiveMoves: true, // Prevent dropping nodes on own descendants
                    dragStart: function (node, data) { return true; },
                    dragEnter: function (node, data) { return true; },
                    dragDrop: function (node, data) { data.otherNode.moveTo(node, data.hitMode); }
                },
                activate: function (event, data) {
                    //alert("activate " + data.node);
                },
                lazyLoad: function (event, data) {
                    //data.result = [{ "title": "Sub item", "lazy": true }, { "title": "Sub folder", "folder": true, "lazy": true }]
                    //[{ "title": "Sub item", "lazy": true }, { "title": "Sub folder", "folder": true, "lazy": true }]
                },
                click: function (event, data) {
                    var node = data.node.data;
                    console.log(node);
                    $("#TerminalDistrictId").val(node.id);
                    $("#hid_DistrictId").val(node.id);
                    $("#datatable").bootstrapTable('refresh');
                    //$("#hid_DistrictId").val("0");
                    $("#TerminalDistrictId").val("0");
                }
            });
            getTreeData();



            //弹出(新增)片区窗口
            $("#btn_add_pq").click(function () {
                var districtId = $("#hid_DistrictId").val();
                var actionUrl = "/Terminal/AddDistrict";
                $(this).showModalAndSubmit($("#DistrictSelectModalWindow"), actionUrl, { districtId: districtId }, "新增片区", $("#DistrictSelectForm"), function () {
                    var validator = $("#DistrictSelectForm").validate({
                        errorClass: "text-danger", validClass: "text-success", errorElement: "em",
                        rules: {
                            Name: {
                                required: true
                            }
                        },
                        messages: {
                            Name: {
                                required: '片区名称不能为空'
                            }
                        },
                        highlight: function (element, errorClass, validClass) {
                            $(element).closest('.field').addClass(errorClass).removeClass(validClass);
                        },
                        unhighlight: function (element, errorClass, validClass) {
                            $(element).closest('.field').removeClass(errorClass).addClass(validClass);
                        },
                        errorPlacement: function (error, element) {
                            if (element.is(":radio") || element.is(":checkbox")) {
                                element.closest('.option-group').after(error);
                            } else {
                                //error.insertAfter(element.parent());
                                element.parent().append(error);
                            }
                        },
                        submitHandler: function (form) {
                            //alert("submitted");
                            form.submit();
                        }
                    });

                    if (!$("#DistrictSelectForm").valid()) {
                        return false;
                    }

                    $(this).remoteSubmit("post", actionUrl, { model: $("#DistrictSelectForm").serializeJson() }, null, function () {
                        $("#DistrictSelectModalWindow").hide();
                        //$("#tree").fancytree();
                        location.href = "/Terminal/List";
                    });
                });
            });

            //弹出(修改)片区窗口
            $("#btn_edit_pq").click(function () {

                var districtId = $("#hid_DistrictId").val();
                if (districtId == "") {
                    $(this).showToastr('请选择片区！');
                    return false;
                }
                var actionUrl = "/Terminal/EditDistrict";
                $(this).showModalAndSubmit($("#DistrictSelectModalWindow"), actionUrl, { districtId: districtId }, "编辑片区", $("#DistrictSelectForm"), function () {
                    debugger
                    var grandParentDistrictId = 0
                    var districtList = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.DistrictList));
                    var parentDistrict = districtList.find(d => {
                        if(d.Id == $("#DistrictParentId").val()) return d;
                    });
                    if (parentDistrict != null) {
                        var grandParentDistrict = districtList.find(d => {
                            if (d.Id == parentDistrict.ParentId) return d;
                        });
                        if (grandParentDistrict == null || grandParentDistrict == undefined || grandParentDistrict == "") {
                            grandParentDistrictId = 0;
                        }
                        else {
                            grandParentDistrictId = grandParentDistrict.Id;
                        }
                    }
                    if ($("#ParentId").val() == null || $("#ParentId").val() == undefined || $("#ParentId").val() == "") {
                        debugger;
                        var test = $("#ParentId").children("option").length;
                        var option = $("#ParentId").children("option").last();
                        option.attr("value", grandParentDistrictId);
                        option.selected = true;
                    }

                    var validator = $("#DistrictSelectForm").validate({
                        errorClass: "text-danger", validClass: "text-success", errorElement: "em",
                        rules: {
                            Name: {
                                required: true
                            },
                            ParentId: {
                                required: true
                            }
                        },
                        messages: {
                            Name: {
                                required: '片区名称不能为空'
                            },
                            ParentId: {
                                required: '片区父类不能为空'
                            }
                        },
                        highlight: function (element, errorClass, validClass) {
                            $(element).closest('.field').addClass(errorClass).removeClass(validClass);
                        },
                        unhighlight: function (element, errorClass, validClass) {
                            $(element).closest('.field').removeClass(errorClass).addClass(validClass);
                        },
                        errorPlacement: function (error, element) {
                            if (element.is(":radio") || element.is(":checkbox")) {
                                element.closest('.option-group').after(error);
                            } else {
                                //error.insertAfter(element.parent());
                                element.parent().append(error);
                            }
                        },
                        submitHandler: function (form) {
                            //alert("submitted");
                            form.submit();
                        }
                    });

                    if (!$("#DistrictSelectForm").valid()) {
                        return false;
                    }

                    $(this).remoteSubmit("post", actionUrl, { model: $("#DistrictSelectForm").serializeJson() }, null, function () {
                        $("#DistrictSelectModalWindow").hide();
                        //$("#tree").fancytree();
                        location.href = "/Terminal/List";
                    });
                });
            });

            //删除片区
            $("#btn_del_pq").click(function () {
                var districtId = $("#hid_DistrictId").val();
                if (districtId == "") {
                    $(this).showToastr('请选择片区！');
                    return false;
                }
                //判读是否已关联到终端
                $(this).remoteSubmit("post", "/Terminal/CheckDisTerminal", { districtId: districtId }, null, function (result) {
                    if (result.Success) {
                        if (result.IncludeTerminal) {
                            $(this).showToastr('该片区已关联终端，不能删除！');
                            return false;
                        }
                        else {
                            WinMsg.confirm({ message: "确认要删除选择的数据吗？" }).on(function (e) {
                                if (!e) {
                                    return;
                                }
                                $(this).remoteSubmit("post", "/Terminal/DeleteDistrict", { districtId: districtId }, null, function () {
                                    //$("#tree").fancytree();
                                    location.href = "/Terminal/List";
                                });
                            });
                        }
                    }
                });
                
            });

            //弹出(新增)终端窗口
            $("#btn_add").click(function () {
                $("#Location_Lng").val("");
                $("#Location_Lat").val("");
                var districtId = $("#hid_DistrictId").val();
                if (districtId == "") {
                    $(this).showToastr('请选择片区！');
                    return false;
                }

                var actionUrl = "/Terminal/AddTerminal";
                $(this).showModalAndSubmit($("#TerminalSelectModalWindow"), actionUrl, { districtId: districtId }, "新增终端", $("#TerminalSelectForm"), function () {
                    var validator = $("#TerminalSelectForm").validate({
                        errorClass: "text-danger", validClass: "text-success", errorElement: "em",
                        rules: {
                            Name: {
                                required: true
                            },
                            MnemonicName: {
                                required: true
                            },
                            BossName: {
                                required: true
                            },
                            BossCall: {
                                required: true
                            },
                            ChannelId: {
                                required: true
                            },
                            PaymentMethod: {
                                required: true
                            }, DistrictId: {
                                required: true
                            },
                            RankId: {
                                required: true
                            }
                        },
                        messages: {
                            Name: {
                                required: '终端名称不能为空'
                            },
                            MnemonicName: {
                                required: '助记名不能为空'
                            },
                            BossName: {
                                required: '老板姓名不能为空'
                            },
                            BossCall: {
                                required: '老板电话不能为空'
                            },
                            ChannelId: {
                                required: '终端渠道不能为空'
                            },
                            PaymentMethod: {
                                required: '付款方式不能为空'
                            },
                            DistrictId: {
                                required: '片区不能为空'
                            },
                            RankId: {
                                required: '终端等级不能为空'
                            }
                        },
                        highlight: function (element, errorClass, validClass) {
                            $(element).closest('.field').addClass(errorClass).removeClass(validClass);
                        },
                        unhighlight: function (element, errorClass, validClass) {
                            $(element).closest('.field').removeClass(errorClass).addClass(validClass);
                        },
                        errorPlacement: function (error, element) {
                            if (element.is(":radio") || element.is(":checkbox")) {
                                element.closest('.option-group').after(error);
                            } else {
                                //error.insertAfter(element.parent());
                                element.parent().append(error);
                            }
                        },
                        submitHandler: function (form) {
                            //alert("submitted");
                            form.submit();
                        }
                    });
                    if (!$("#TerminalSelectForm").valid()) {
                        return false;
                    }

                    $("#Location_Lng").val($("#txtLocation_Lng").val());
                    $("#Location_Lat").val($("#txtLocation_Lat").val());

                    $(this).remoteSubmit("post", actionUrl, { model: $("#TerminalSelectForm").serializeJson() }, null, function () {
                        $("#datatable").bootstrapTable('refresh');
                        $("#TerminalSelectModalWindow").modal('hide');
                    });
                });
            });
            $("#ddl_Status").change(function () {
                var s = $("#ddl_Status").val();
                if (s == 'true') {
                    $("#btn_batchDisable").html("<span class=\"fa fa-trash-o mr5\" aria-hidden=\"true\"></span>批量禁用");
                    $("#btn_batchDisable").attr("type", true);

                } else {
                    $("#btn_batchDisable").html("<span class=\"fa fa-check mr5\" aria-hidden=\"true\"></span>批量启用");
                    $("#btn_batchDisable").attr("type", false);
                }
                $("#datatable").bootstrapTable('refresh');
            });

            //批量匹配片区
            $("#batchAssignDistrict").click(function () {
                var arrselections = $("#datatable").bootstrapTable('getSelections');
                if (arrselections.length == 0) {
                    $(this).showToastr('请选择要指定片区的终端！');
                    return false;
                }
                //alert()
                var actionUrl = "/Terminal/BatchAssignDistrict";
                $(this).showModalAndSubmit($("#BatchAssignDistrictModalWindow"), actionUrl, null, "批量匹配片区", $("#BatchAssignDistrictForm"), function () {
                        //$('#btnSave_BatchAssignDistrictModalWindow').unbind();
                        var AssignDistrictId = $("#hid_AssignDistrictId").val();
                        var allTableData = $('#datatable').bootstrapTable('getSelections').map(item => { return item.Id; });
                        $('#BatchAssignDistrictModalWindow').modal('hide');
                        //保存的数据
                        var postData =
                        {
                            //片区id
                            did: AssignDistrictId,
                            //终端IDs
                            tids: allTableData,
                            isAll: false
                        };
                        //保存服务器
                        $(this).remoteSubmit("post", "/Terminal/BatchAssignDistrict", postData, null, function (data) {
                            if (data.Success) {
                                $('#BatchAssignDistrictModalWindow').modal('hide');
                            }
                        }, null, null);

                });
            });

            //全部匹配片区
            $("#allAssignDistrict").click(function () {
                //alert()
                var actionUrl = "/Terminal/BatchAssignDistrict";
                $(this).showModalAndSubmit($("#BatchAssignDistrictModalWindow"), actionUrl, null, "批量匹配片区", $("#BatchAssignDistrictForm"), function () {
                    //$('#btnSave_BatchAssignDistrictModalWindow').unbind();
                    var AssignDistrictId = $("#hid_AssignDistrictId").val();
                    $('#BatchAssignDistrictModalWindow').modal('hide');
                    if (AssignDistrictId == 0) {
                        $(this).showToastr('请选择要指定的片区！');
                        return false;
                    }
                    //保存的数据
                    var postData =
                    {
                        //片区id
                        did: AssignDistrictId,
                        //终端IDs
                        tids: [],
                        isAll: true
                    };
                    //保存服务器
                    $(this).remoteSubmit("post", "/Terminal/BatchAssignDistrict", postData, null, function (data) {
                        if (data.Success) {
                            $('#BatchAssignDistrictModalWindow').modal('hide');
                        }
                    }, null, null);

                });
            });

            //批量匹配渠道
            $("#batchAssignChannel").click(function () {
                var arrselections = $("#datatable").bootstrapTable('getSelections');
                if (arrselections.length == 0) {
                    $(this).showToastr('请选择要指定渠道的终端！');
                    return false;
                }
                //alert()
                var actionUrl = "/Terminal/AsyncBatchAssignChannel";
                $(this).showModalAndSubmit($("#BatchAssignChannelModalWindow"), actionUrl, null, "批量匹配渠道", $("#BatchAssignChannelForm"), function () {
                    //$('#btnSave_BatchAssignDistrictModalWindow').unbind();
                    var AssignChannelId = $("#hid_AssignChannelId").val();
                    var allTableData = $('#datatable').bootstrapTable('getSelections').map(item => { return item.Id; });
                    $('#BatchAssignChannelModalWindow').modal('hide');
                    //保存的数据
                    var postData =
                    {
                        //渠道id
                        cid: AssignChannelId,
                        //终端IDs
                        tids: allTableData,
                        isAll: false
                    };
                    //保存服务器
                    $(this).remoteSubmit("post", "/Terminal/BatchAssignChannel", postData, null, function (data) {
                        if (data.Success) {
                            $('#BatchAssignChannelModalWindow').modal('hide');
                        }
                    }, null, null);

                });
            }); 


            //批量禁用
            $("#btn_batchDisable").click(function ()
            {
                var arrselections = $("#datatable").bootstrapTable('getSelections');
                if (arrselections.length == 0) {
                    $(this).showToastr('请选择要禁用的终端！');
                    return false;
                }
                var ids = [];
                arrselections.forEach(function (a, b) {
                    ids.push(a.Id);
                });

                var url = "/Terminal/BatchDisable?ids=" + ids;
                var type = $(this).attr("type");
                url = "/Terminal/BatchDisable?type=" + type + "&ids=" + ids;
                $.ajax({
                    type: 'get',
                    url: url,
                    async: true,
                    success: function (res) {
                        $(this).showToastr('操作成功！');
                        $("#datatable").bootstrapTable('refresh');
                    }
                });
            });


            //全部匹配渠道
            $("#allAssignDistrict").click(function () {
                //alert()
                var actionUrl = "/Terminal/AsyncBatchAssignChannel";
                $(this).showModalAndSubmit($("#BatchAssignChannelModalWindow"), actionUrl, null, "批量匹配渠道", $("#BatchAssignChannelForm"), function () {
                    //$('#btnSave_BatchAssignDistrictModalWindow').unbind();
                    var AssignChannelId = $("#hid_AssignChannelId").val();
                    $('#BatchAssignChannelModalWindow').modal('hide');
                    if (AssignChannelId== 0) {
                        $(this).showToastr('请选择要指定的渠道！');
                        return false;
                    }
                    //保存的数据
                    var postData =
                    {
                        //渠道id
                        cid: [],
                        //终端IDs
                        tids: allTableData,
                        isAll:true
                    };
                    //保存服务器
                    $(this).remoteSubmit("post", "/Terminal/BatchAssignChannel", postData, null, function (data) {
                        if (data.Success) {
                            $('#BatchAssignChannelModalWindow').modal('hide');
                        }
                    }, null, null);

                });
            }); 

            //终端列表
            $("#datatable").bootstrapTable({
                url: "/Terminal/TerminalList",         //请求后台的URL（*）
                method: 'get',                      //请求方式（*）
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,                   //是否显示分页（*）
                showPagination: false,
                queryParams: function (params) {
                    var temp =
                    {
                        districtId: $("#hid_DistrictId").val(),
                        searchStr: $("#txt_searchStr").val(),
                        channelId: $("#ddl_Channel").val(),
                        rankId: $("#ddl_Rank").val(),
                        status: $("#ddl_Status").val(),
                        pageSize: params.limit,   //页面显示行数
                        pageIndex: (params.offset / params.limit)  //页码
                    };
                    return temp;
                },
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                idField: 'Id',
                pageNumber: 1,                       //初始化加载第一页，默认第一页
                pageSize: 15,                       //每页的记录行数（*）
                pageList: [15, 25, 50, 100],        //可供选择的每页的行数（*）
                search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                strictSearch: true,
                showRefresh: false,                  //是否显示刷新按钮
                //minimumCountColumns: 2,           //最少允许的列数
                clickToSelect: true,                //是否启用点击选中行
                //height: 520,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                uniqueId: "Id",                     //每一行的唯一标识，一般为主键列
                showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
                cardView: false,                    //是否显示详细视图
                detailView: false,                   //是否显示父子表
                columns: [
                    { checkbox: true, visible: true },
                    {
                        title: '<i class="fa fa-gear fs18"></i>', formatter: function (value, row, index) {
                            return m_pagerow + index + 1;
                        }
                    },
                    { field: 'Name', title: '终端名称', align: 'left' },
                    { field: 'Code', title: '终端编号', align: 'left' },
                    { field: 'BossName', title: '老板名称', align: 'left' },
                    { field: 'BossCall', title: '老板手机', align: 'center' },
                    { field: 'Address', title: '老板地址', align: 'left' },
                    { field: 'DistrictName', title: '片区', align: 'left' },
                    { field: 'LineName', title: '线路', align: 'left' },
                    { field: 'ChannelName', title: '渠道', align: 'left' },
                    { field: 'RankName', title: '等级', align: 'left' },
                    {
                        field: 'PaymentMethod',
                        title: '付款方式',
                        align: 'center',
                        formatter: function (value, row, index) {
                            if (value == '1') {
                                return "现结";
                            } else {
                                return "挂账";
                            }
                        }
                    },
                    {
                        field: 'Status',
                        title: '状态', align: 'center',
                        formatter: function (value, row, index) {
                            if (value) {
                                return '<span class="label label-success">正常</span>';
                            } else {
                                return '<span class="label label-default">停用</span>';
                            }
                        }
                    },
                    {
                        field: 'operate', title: '操作', align: 'center', width: '150', events: {
                            'click .rowrecords': function (e, value, row, index) {
                            },
                            'click .rowdel': function (e, value, row, index) {
                                WinMsg.confirm({ message: "确认要删除选择的数据吗？" }).on(function (e) {
                                    if (!e) {
                                        return;
                                    }
                                    $(this).remoteSubmit("post", "/Terminal/DeleteTerminal", { ids: row.Id }, $("#datatable"), null);
                                });
                            },
                            'click .rowedit': function (e, value, row, index) {
                                //console.log("row.Id:" + row.Id);
                                var actionUrl = "/Terminal/EditTerminal";
                                $(this).showModalAndSubmit($("#TerminalSelectModalWindow"), actionUrl, { id: row.Id }, "编辑终端", $("#TerminalSelectForm"), function () {
                                    var validator = $("#TerminalSelectForm").validate({
                                        errorClass: "text-danger", validClass: "text-success", errorElement: "em",
                                        rules: {
                                            Name: {
                                                required: true
                                            },
                                            MnemonicName: {
                                                required: true
                                            },
                                            BossName: {
                                                required: true
                                            },
                                            BossCall: {
                                                required: true
                                            },
                                            ChannelId: {
                                                required: true
                                            },
                                            PaymentMethod: {
                                                required: true
                                            }, DistrictId: {
                                                required: true
                                            },
                                            RankId: {
                                                required: true
                                            },
                                            BusinessNo: {
                                                required: true
                                            },
                                            EnterpriseRegNo: {
                                                required: true
                                            },
                                            FoodBusinessLicenseNo: {
                                                required: true
                                            }
                                        },
                                        messages: {
                                            Name: {
                                                required: '终端名称不能为空'
                                            },
                                            MnemonicName: {
                                                required: '助记名不能为空'
                                            },
                                            BossName: {
                                                required: '老板姓名不能为空'
                                            },
                                            BossCall: {
                                                required: '老板电话不能为空'
                                            },
                                            ChannelId: {
                                                required: '终端渠道不能为空'
                                            },
                                            PaymentMethod: {
                                                required: '付款方式不能为空'
                                            },
                                            DistrictId: {
                                                required: '片区不能为空'
                                            },
                                            RankId: {
                                                required: '终端等级不能为空'
                                            },
                                            BusinessNo: {
                                                required: '营业编号不能为空'
                                            },
                                            EnterpriseRegNo: {
                                                required: '企业注册号不能为空'
                                            },
                                            FoodBusinessLicenseNo: {
                                                required: '经营许可证不能为空'
                                            }

                                        },
                                        highlight: function (element, errorClass, validClass) {
                                            $(element).closest('.field').addClass(errorClass).removeClass(validClass);
                                        },
                                        unhighlight: function (element, errorClass, validClass) {
                                            $(element).closest('.field').removeClass(errorClass).addClass(validClass);
                                        },
                                        errorPlacement: function (error, element) {
                                            if (element.is(":radio") || element.is(":checkbox")) {
                                                element.closest('.option-group').after(error);
                                            } else {
                                                //error.insertAfter(element.parent());
                                                element.parent().append(error);
                                            }
                                        },
                                        submitHandler: function (form) {
                                            //alert("submitted");
                                            form.submit();
                                        }
                                    });
                                    if (!$("#TerminalSelectForm").valid()) {
                                        return false;
                                    }

                                    if ($("#Location_Lng").val() != $("#txtLocation_Lng").val()) {
                                        $("#Location_Lng").val($("#txtLocation_Lng").val());
                                    }

                                    if ($("#Location_Lat").val() != $("#txtLocation_Lat").val()) {
                                        $("#Location_Lat").val($("#txtLocation_Lat").val());
                                    }

                                    $(this).remoteSubmit("post", actionUrl, { model: $("#TerminalSelectForm").serializeJson() }, null,
                                        function () {
                                            $("#datatable").bootstrapTable('refresh');
                                            $("#TerminalSelectModalWindow").modal('hide');
                                        });

                                    //====

                                });
                            }
                        }, formatter: function (value, row, index) {
                            return [
                                '<button type="button" class="btn btn-sm btn-info rowedit mr5"><i class="fa fa-pencil-square-o mr5"></i>编辑</button>',
                                '<button type="button" class="btn btn-sm btn-danger rowdel"><i class="fa fa-trash-o mr5"></i>删除</button>'
                                //二期开发
                                //'<button type="button" class="btn btn-sm btn-default rowrecords"><i class="fa fa-search-plus mr5"></i>记录</button>'
                            ].join('');
                        }
                    }
                ],
                onPageChange: function (number, size) {
                    m_pagerow = (number - 1) * size;
                },
                onLoadSuccess: function (data) {
                    console.log('load');
                }
            });
            //终端检索
            //var searchCensus = function () {
            //    //保存服务器
            //    $(this).remoteSubmit("post", "/Terminal/SearchGensus", { model: $("#TerminalSelectForm").serializeJson() }, null, function (result) {
            //        //TODO 绑定到搜索框下拉，选择后赋值到model的精度纬度坐标字段上
            //        var list = result.data;
            //    });
            //}

            //查询
            $("#btn_query").click(function ()
            {
                var key = $("#txt_searchStr").val();
                if (key == "" || key == null) {
                    $(this).showToastr('请输入查询关键字！');
                    return false
                }

                $("#datatable").bootstrapTable('refresh', {
                    url: "/Terminal/TerminalList", silent: true, query: {
                        //districtId: $("#hid_DistrictId").val(),
                        districtId: 0,
                        searchStr: key,
                        channelId: $("#ddl_Channel").val(),
                        rankId: $("#ddl_Rank").val(),
                        status: $("#ddl_Status").val()
                    }
                });
            });

            //导入档案
            $("#btn_importProduct").click(function () {
                $("#hidDistrictId").val('');
                var districtId = $("#hid_DistrictId").val();
                if (districtId == "") {
                    $(this).showToastr('请选择片区！');
                    return false;
                }

                $("#hidDistrictId").val(districtId);
                $('#TerFileForm').modal('show');
            });

            $("#excel_import").click(function () {
                var file = $('#file').val();
                if (file == "") {
                    $(this).showToastr('请选择文件！');
                    return false;
                }
                //$("#formImport").submit();
                $.ajax({
                    url: "/Terminal/Import",
                    type:'post',
                    async: true,
                    data: new FormData($("#formImport")[0]),
                    cache: false,
                    contentType: false,    //不可缺
                    processData: false,
                    success: function (result) {
                        if (result.Success) {
                            $('#TerFileForm').modal('hide');
                            $("#datatable").bootstrapTable('refresh', {
                                url: "/Terminal/TerminalList", silent: true, query: {
                                    districtId: 0,
                                    searchStr: '',
                                    channelId: $("#ddl_Channel").val(),
                                    rankId: $("#ddl_Rank").val(),
                                    status: $("#ddl_Status").val()
                                }
                            });
                        } else {
                            $(this).showToastr(result.Message);
                        }
                    }
                });
            });
            //=====================================================终端结束=========================================================================

        });
        //数组转树结构
        //[{ Id: 1, Name: "一级分类：1", ParentId: 0, }, { Id: 2, Name: "二级分类：1", ParentId: 1, }]
        var toTree = function (data) {
            var newdata = [];
            data.forEach(function (item) {
                var tempdata = { title: item.Name, key: item.Id, pid: item.ParentId, expanded: true, folder: false };
                newdata.push(tempdata);
            });

            // 删除 所有 children,以防止多次调用
            newdata.forEach(function (item) {
                delete item.children;
            });
            // 将数据存储为 以 id 为 KEY 的 map 索引数据列
            var map = {};
            newdata.forEach(function (item) {
                map[item.key] = item;
            });
            //        console.log(map);
            var val = [];
            newdata.forEach(function (item) {
                // 以当前遍历项，的pid,去map对象中找到索引的id
                var parent = map[item.pid];
                // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
                if (parent) {
                    var temp = (parent.children || (parent.children = []));
                    temp.push(item);
                    if (temp.length > 0) parent.folder = true;
                } else {
                    //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
                    item.folder = true;
                    val.push(item);
                }
            });
            return val;
        }
    </script>
}
